<?php
namespace app\payqr\model;
use app\admin\model\ShopOrder;
use app\BaseModel;
use think\facade\Db;

class CardCompany extends BaseModel
{
    protected $name = 'longbing_card_company';
    public function companyInfo($uid,$uniacid){

        $dis['b.fans_id'] = $uid;
        $data = $this
            ->alias('a')
            ->leftJoin('longbing_card_user_info b' ,'a.id = b.company_id')
            ->where($dis)
            ->field('a.*','b.fans_id')
            ->find();
        if(empty($data)){
            $data = $this->where(['uniacid'=>$uniacid])->find();
        }
        return $data;
    }
    public function getlist($where){
        $companyList = $this->where($where)
            ->order('top desc,create_time desc')
            ->field( [ 'id', 'pid', 'name', 'addr', 'status','top' ] )
            ->select()
            ->toArray();
        return $companyList;
    }
    public function getImg($where){
        $culture = $this->where($where)->value('culture');
        $data = [];
        if($culture){
            $data = transImages([$culture],['culture'])[0];
        }
        return $data;
    }
    /**
     * @Purpose: 处理公司层级--无限级
     *
     * @Param: array $list 顶级公司列表
     * @Param: array $son 部门列表
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function handleCompanyLevel ( $list, $son, $item_name = 'sec' )
    {
        foreach ( $list as $index => $item )
        {
            if ( !isset( $list[ $index ][ $item_name ] ) )
            {
                $list[ $index ][ $item_name ] = array();
            }
            foreach ( $son as $key => $value )
            {
                if ( $item[ 'id' ] == $value[ 'pid' ] )
                {
                    array_push( $list[ $index ][ $item_name ], $value );
                    unset( $son[ $key ] );
                }
            }

            if ( $list[ $index ][ $item_name ] && count( $list[ $index ][ $item_name ] ) && count( $son ) )
            {

                $list[ $index ][ $item_name ] = self::handleCompanyLevel( $list[ $index ][ $item_name ], $son, $item_name );
            }
        }
        return $list;
    }
    public function getCompanyUser($id){
        static $arr = [];
        $data = $this->alias( 'a' )
            ->join( 'longbing_card_user_info b', 'b.company_id = a.id')
            ->where('a.pid',$id)
            ->where('b.status',1)
            ->where('a.status','<>',-1)
            ->field('a.id,a.pid')
            ->select()->toArray();
        if($data){
            foreach ($data as $key=>$val){
                $arr[] = $val['id'];
                $this->getCompanyUser($val['id']);
            }
        }
        return $arr;
    }
    //返回公司最上级id
    public function getUserTopCompanyId($company_id){
        $data = $this->where('id',$company_id)->field('id,pid')->find();
        $arr =[];
        if($data){
            $arr = $this->getUserTopCompanyId($data['pid']);
            if(empty($arr)){
                return $data['id'];
            }
        }
        return $arr;
    }
    public function getCompanyName($company_id){
        return $this->whereIn('id',$company_id)->column('name','id');
    }
    /**
     * @Purpose: 改变公司状态
     *
     * @Param：$company_id   number  公司id
     * @Param：$method   number  操作类型  0 = 下架 1 = 上架 2 = 删除
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function updateStatus ( $company_id, $method = 0 )
    {
        switch ( $method )
        {
            case 0:
                $result = self::update( [ 'status' => 0 ], [ 'id' => $company_id ] );
                $this->updateSonCompanyInfo( $company_id, [ 'status' => 0 ] );
                break;
            case 1:
                $result = self::update( [ 'status' => 1 ], [ 'id' => $company_id ] );
                break;
            case 2:
                $result = self::update( [ 'status' => -1 ], [ 'id' => $company_id ] );
                $this->updateSonCompanyInfo( $company_id, [ 'status' => -1 ] );
                break;
            default:
                return false;
        }

        if ( $result === false )
        {
            return false;
        }

        return $result;
    }
    /**
     * @Purpose: 改变下级公司信息
     *
     * @Param：$company_id   number  公司id
     * @Param：$data   array  修改内容
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function updateSonCompanyInfo ( $company_id, $data )
    {
        $list = self::where( [ [ 'pid', '=', $company_id ] ] )
            ->select()
            ->toArray();

        foreach ( $list as $index => $item )
        {
            $check = self::where( [ [ 'pid', '=', $item[ 'id' ] ] ] )
                ->count();
            if ( $check )
            {
                $this->updateSonCompanyInfo( $item[ 'id' ], $data );
            }
            self::update( $data, [ 'id' => $item[ 'id' ] ] );
        }

        return true;
    }

    public function getinfo($where,$type=0){
        $data = $this->where($where)->find();
        if($data){
            $data = $data->toArray();
            if($type==0){
                $data  = transImages( $data, [ 'logo', 'desc', 'culture' ] );
            }
        }
        return $data;
    }
    //查询小程序下公司的列表
    public function getCompanyUserNumber($where){
        $data = $this->alias('a')
            ->join( 'longbing_card_user_info b', 'a.id = b.company_id and b.is_staff = 1 and b.status = 1','left')
            ->field('a.short_name as name,count(b.company_id) as number,a.id,a.uniacid')
            ->where($where)
            ->where('pid','=',0)
            ->group('a.id')
            //->limit(5)
            ->select()->toArray();
        if($data){
            $user_info = new UserInfo();
            foreach ($data as $key=>$val){
                //查询公司下面所有公司
                $Company_list =$this->getCompanyUser_l($val['id']);
                if($Company_list){
                    $user_count = $user_info->getCoampanyStaff($Company_list);
                    $data[$key]['number'] = round($val['number']+$user_count,2);
                }
            }
            $last_names = array_column($data,'number');
            array_multisort($last_names,SORT_DESC,$data);
            $data = array_slice($data, 0, 5);
            $totla_number = array_sum(array_column($data,'number'));
            foreach ($data as $k=>$v){
                if($totla_number<=0){
                    $proportion = 100;
                }else{
                    $proportion = round($v['number']/$totla_number*100,2);
                }
                $data[$k]['proportion'] = $proportion;
            }
        }

        return $data;
    }
    // public function top($company_id){
    // 	return $this->where()->
    // }
    public $sss=[];
    //查询公司下的所有子公司
    public function getCompanyUser_l($company_id,$arr1 = []){
        static $arr = [];
        //$arr1 = [];
        if(!$arr1){
            $arr = [];
        }

        $data = $this
            //->alias( 'a' )
            //->join( 'longbing_card_user_info b', 'b.company_id = a.id','left')
            ->where('pid',$company_id)
            ->where('status',1)
            ->field('id,pid,name')
            ->select()->toArray();

        if($data){
            foreach ($data as $key=>$val){

                $arr[] = $val['id'];
                $this->getCompanyUser_l($val['id'],$arr);

            }
        }
        return $arr;
    }
    //查询下一级公司id
    public function getCompanyUser_top($company_id){
        $data = $this
            ->where('pid',$company_id)
            ->where('status',1)
            ->column('id');
        return $data;
    }
    public function getJobUser($company_id,$uniacid){
        $company = $this->getCompanyUser_top($company_id);
        $data = $this->alias('a')
            ->join( 'longbing_card_user_info b', 'a.id = b.company_id and b.is_staff =1','left')
            ->field('count(b.id) as number,a.name,a.id,a.uniacid')
            ->whereIn('a.id',$company)
            ->where('a.uniacid',$uniacid)
            ->order('number','desc')
            ->group('a.id')
            //->limit(5)
            ->select()->toArray();
        if($data){
            $user_info = new UserInfo();
            //获取总的部门人数
            foreach ($data as $key=>$val){

                $Company_list =$this->getCompanyUser_l($val['id']);
                if($Company_list){
                    $user_count = $user_info->getCoampanyStaff($Company_list);
                    $data[$key]['number'] = $val['number']+$user_count;
                }
            }
            $last_names = array_column($data,'number');
            array_multisort($last_names,SORT_DESC,$data);
            $data = array_slice($data, 0, 5);
            $totla_number = array_sum(array_column($data,'number'));
            foreach ($data as $k=>$v){
                if($totla_number<=0){
                    $proportion = 100;
                }else{
                    $proportion = round($v['number']/$totla_number*100,2);
                }
                $data[$k]['proportion'] = $proportion;
            }

        }
        return $data;
    }
    public function getCompanyJobUser($where){
        $this->where($where)->count();
    }

//    //查询排行笔数
//    public function getOrderCount($where){
//        $data = $this->alias('a')
//            ->where($where)
//            ->join( 'longbing_card_shop_order b', 'a.id = b.company_id and pay_status=1 and order_status=3','left')
//            ->field('count(b.id) as number,a.id,a.name')
//            ->where('a.status',1)
//            ->limit(5)
//            ->order('number','desc')
//            ->group('a.id')
//            ->select()->toArray();
//        return $data;
//    }
    public function getCreateTimeAttr($value){
        return date('Y-m-d H:i:s',$value['create_time']);
    }
    //查询销售业绩
    public function getOrderSum($where,$time){
        $aa = '';
        if($time == '-7 day'||$time == '-15 day'||$time == '-30 day'){
            $start=strtotime("$time");
            $end=time();
            $aa = "and b.create_time BETWEEN $start AND $end";
        }
        $data = $this->alias('a')
            ->where($where)
            ->join( 'longbing_card_shop_order b', "a.id = b.company_id and pay_status=1 and order_status=3 $aa",'left')
            ->field('sum(total_price) as money,a.id,a.short_name,a.name,pid,b.create_time,b.company_id')
            //->limit(5)
            ->where('a.status',1)
            ->order('money','desc')
            ->group('a.id')
            ->select()->toArray();
        if($data){
            $shop_order = new ShopOrder();
            foreach ($data as $key=>$val){
                $Company_list =$this->getCompanyUser_l($val['id']);
                if($Company_list){
                    $all_price =$shop_order->getCompanyPrice($Company_list,$start,$end);
                    $data[$key]['money'] = round($all_price+$val['money'],2);
                }
            }
            $last_names = array_column($data,'money');
            array_multisort($last_names,SORT_DESC,$data);
            $data = array_slice($data, 0, 5);
        }
        return $data;
    }
    public function getCompanylist($where){
        $data = $this->where($where)->column('id');
        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-21 14:02
     * @功能说明:替换顶级公司的名字
     */

    public function changeTopName($company){

        if(!empty($company['top_id'])){

            $dis = [

                'status' => 1,

                'id'     => $company['top_id'],

                'uniacid'=> $company['uniacid']

            ];

            $top_name = $this->where($dis)->value('name');

            $short_name = $this->where($dis)->value('short_name');

            if(!empty($top_name)){

                $company['name'] = $top_name;

                $company['short_name'] = $short_name;

            }
        }

        return $company;
    }
}